<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入菜品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜品分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择菜品分类" clearable @change="handleQuery">
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="菜品价格" prop="price">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.price"-->
      <!--          placeholder="请输入菜品价格"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="售卖状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.sc_dish_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dish:dish:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dish:dish:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dish:dish:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dishList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center">
        <!--        每页的序号都从1开始-->
        <!--        <template slot-scope="scope">-->
        <!--          {{ scope.$index + 1 }}-->
        <!--        </template>-->
        <!--        不间断序号-->
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="菜品名称" align="center" prop="name"/>
      <el-table-column label="菜品分类" align="center">
        <template slot-scope="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>

      <el-table-column label="菜品价格" align="center" prop="price"/>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="描述信息" align="center" prop="description"/>
      <el-table-column label="售卖状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sc_dish_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="商户id" align="center" prop="merchantId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dish:dish:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dish:dish:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改菜品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜品名称"/>
        </el-form-item>
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择菜品分类" clearable>
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="菜品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入菜品价格"/>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述信息"/>
        </el-form-item>
        <el-form-item label="售卖状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.sc_dish_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="商户id" prop="merchantId">-->
        <!--          <el-input v-model="form.merchantId" placeholder="请输入商户id" />-->
        <!--        </el-form-item>-->
        <el-divider content-position="center">菜品口味信息</el-divider>

        <el-table :data="flavors" :row-class-name="rowScDishFlavorIndex"
                  @selection-change="handleScDishFlavorSelectionChange" ref="scDishFlavor">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="口味名称" prop="name" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.name" placeholder="请选择口味种类">
                <el-option
                  v-for="flavor in dishFlavorsData"
                  :key="flavor.name"
                  :label="flavor.name"
                  :value="flavor.name"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="口味数据" prop="value" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.value" placeholder="请选择口味">
                <el-option
                  v-for="item in getFlavorOptions(scope.row.name)"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddScDishFlavor">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteScDishFlavor">删除
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listDish, getDish, delDish, addDish, updateDish} from "@/api/smartcanteen/dish";
import {listCategory} from "@/api/smartcanteen/category";

export default {
  name: "Dish",
  dicts: ['sc_dish_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedScDishFlavor: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜品管理表格数据
      dishList: [],
      // 菜品口味关系表格数据
      flavors: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        name: null,
        categoryId: null,
        price: null,
        status: null,
        merchantId: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "菜品名称不能为空", trigger: "blur"}
        ],
        categoryId: [
          {required: true, message: "菜品分类不能为空", trigger: "blur"}
        ],
      },
      dishFlavorsData: [
        {name: '口味', list: ['原味', '番茄', '黑椒', '沙拉', '麻辣']},
        {name: '甜味', list: ['无糖', '少糖', '半糖', '多糖', '全糖']},
        {name: '温度', list: ['热饮', '常温', '去冰', '少冰', '多冰']},
        {name: '忌口', list: ['不要葱', '不要蒜', '不要香菜', '不要辣']},
        {name: '辣度', list: ['不辣', '微辣', '中辣', '重辣']}
      ],
      categoryList: [],
    };
  },
  created() {
    this.getList();
    this.getCategoryList();
  },
  methods: {
    // 根据分类ID获取分类名称
    getCategoryName(categoryId) {
      const category = this.categoryList.find(item => item.id === categoryId);
      return category ? category.name : '未添加分类';
    },
    /** 根据口味名称获取口味数据选项 */
    getFlavorOptions(flavorName) {
      const flavorData = this.dishFlavorsData.find(flavor => flavor.name === flavorName);
      return flavorData ? flavorData.list : [];
    },
    /** 查询菜品管理列表 */
    getList() {
      this.loading = true;
      listDish(this.queryParams).then(response => {
        this.dishList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 查询菜品分类列表 */
    getCategoryList() {
      listCategory({page: 1, pageSize: 10000}).then(response => {
        this.categoryList = response.data.records;
      }).catch(error => {
        console.error("获取分类列表失败:", error);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        categoryId: null,
        price: null,
        image: null,
        description: null,
        status: 1,
        merchantId: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null
      };
      this.flavors = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加菜品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDish(id).then(response => {
        this.form = response.data;
        this.flavors = response.data.flavors;
        this.open = true;
        this.title = "修改菜品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 提取 flavors 中的 name 和 value 字段
          const filteredScDishFlavorList = this.flavors.map(flavor => ({
            name: flavor.name,
            value: flavor.value
          }));

          this.form.flavors = filteredScDishFlavorList;
          if (this.form.id != null) {
            updateDish(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDish(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$modal.confirm('是否确认删除菜品管理编号为"' + ids + '"的数据项？').then(function () {
        // const ids = (row.id ? [row.id] : this.ids).join(',');
        return delDish(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 菜品口味关系序号 */
    rowScDishFlavorIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 菜品口味关系添加按钮操作 */
    handleAddScDishFlavor() {
      let obj = {};
      obj.name = "";
      obj.value = "";
      this.flavors.push(obj);
    },
    /** 菜品口味关系删除按钮操作 */
    handleDeleteScDishFlavor() {
      if (this.checkedScDishFlavor.length === 0) {
        this.$modal.msgError("请先选择要删除的菜品口味关系数据");
      } else {
        const flavors = this.flavors;
        const checkedScDishFlavor = this.checkedScDishFlavor;
        this.flavors = flavors.filter(function (item) {
          return checkedScDishFlavor.indexOf(item.index) === -1
        });
      }
    },
    /** 复选框选中数据 */
    handleScDishFlavorSelectionChange(selection) {
      this.checkedScDishFlavor = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dish/dish/export', {
        ...this.queryParams
      }, `dish_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
